<?php

class GroupController extends CommonController {
	
	public function __construct() {
		parent::__construct();
	}
	
	public function recordsAction(){
		$page = (int) $this->requestGet('page', 1);
		$pageSize = (int) $this->requestGet('pageSize', 100);
		$offset = ($page - 1) * $pageSize;

		$orderField = (int) $this->requestGet('orderField', 0);
		$orderDirection = (int) $this->requestGet('orderDirection', 1);
		$fields = array('name');
		$field = isset($fields[$orderField]) ? $fields[$orderField] : $field[0];
		$direction = $orderDirection > 0 ? 'ASC' : 'DESC';
		$order = " ORDER BY `{$field}` {$direction} ";

		$totalQuery = "SELECT COUNT(`id`) as `total` FROM `group`";
		$db = $this->loadSqlite('bamboo');
		$totalRow = $db->getOne($totalQuery);
		$data = array('total' => $totalRow['total']);
		
		$query = "SELECT * FROM `group` WHERE 1 {$order} LIMIT {$offset}, {$pageSize}";
		$data['records'] = $db->getAll($query);

		$this->jsonSuccess('', $data);
	}
	
	public function simpleAction(){
		$db = $this->loadSqlite('bamboo');
		$query = "SELECT `id`, `name` FROM `group`";
		$records = $db->getAll($query);
		$result = array();
		foreach($records as $record){
			$result[$record['id']] = $record['name'];
		}
		$this->jsonSuccess('', $result);
	}
	
	public function findAction() {
		$id = (int) $this->requestGet('id');
		if (!$id)
			$this->jsonError('参数错误');
		$findQuery = "SELECT * FROM `group` WHERE `id`={$id}";
		$db = $this->loadSqlite('bamboo');
		$row = $db->getOne($findQuery);
		$this->jsonSuccess('', $row);
	}
	
	public function setAction(){
		$id = (int) $this->requestPost('id');
		$data = array(
			'name' => (string) $this->requestPost('name')
		);
		$db = $this->loadSqlite('bamboo');
		if ($db->set('group', $data, $id)) {
			$this->jsonSuccess('保存成功');
		} else {
			$this->jsonError('保存失败 ' . $db->errorMessage);
		}
	}

	public function permissionAction(){
		$id = (int) $this->requestPost('id');
		$permissions = $this->requestPost('permission');
		$data = array(
			'permissions' => implode(',', $permissions)
		);

		$db = $this->loadSqlite('bamboo');
		if ($db->set('group', $data, $id)) {
			$this->jsonSuccess('分配成功');
		} else {
			$this->jsonError('分配失败 ' . $db->errorMessage);
		}	
	}
}
?>